package com.aiti.lulian.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.utils.message.Message;
import com.aiti.base.core.utils.stringUtil.StringUtil;
import com.aiti.lulian.dto.CommunicateInfoDto;
import com.aiti.lulian.dto.CommunicateInfoImportDto;
import com.aiti.lulian.dto.CommunicateInfoSaveDto;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.mapper.CommunicateInfoMapper;
import com.aiti.lulian.service.CardBusinessCollaboratorService;
import com.aiti.lulian.service.ICommunicateInfoService;
import com.aiti.lulian.service.ILuLianEnterpriseUserService;
import com.aiti.lulian.service.ISysDataService;
import com.aiti.lulian.utils.DateFilterUtil;
import com.aiti.lulian.vo.CommunicateInfoExportVo;
import com.aiti.lulian.vo.CommunicateInfoVo;
import com.aiti.lulian.vo.EmployeeOpportunityCountVo;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CommunicateInfoServiceImpl extends BaseSerivceImpl<CommunicateInfoMapper, CommunicateInfo> implements ICommunicateInfoService {


    private final CommunicateInfoMapper communicateInfoMapper;

    private final ILuLianEnterpriseUserService luLianService;

    private final CloudShowManagerSubService scaleUserService;

    @Autowired
    private CloudShowManagerSubService cloudShowManagerSubService;
    @Autowired
    private ISysDataService sysDataService;

    @Autowired
    private CardBusinessCollaboratorService cardBusinessCollaboratorService;

    @Autowired
    private ILuLianEnterpriseUserService luLianEnterpriseUserService;

    public CommunicateInfoServiceImpl(CommunicateInfoMapper communicateInfoMapper, ILuLianEnterpriseUserService luLianService, CloudShowManagerSubService scaleUserService) {
        this.communicateInfoMapper = communicateInfoMapper;
        this.luLianService = luLianService;
        this.scaleUserService = scaleUserService;
    }

    /**
     * 立即沟通
     *
     * @param communicateInfo
     */
    @Override
    public Message commitCommunicateInfo(CommunicateInfo communicateInfo) {

        if (StringUtil.isBlank(communicateInfo.getProductName()) || StringUtil.isBlank(communicateInfo.getCallName()) || StringUtil.isBlank(communicateInfo.getPhone())) {
            return Message.fail("缺少必传参数");
        }
        communicateInfo.setType("1");
        boolean save = this.save(communicateInfo);
        if (save) return Message.success("保存成功");
        return Message.fail("保存失败");
    }

    @Override
    public Map<String, Object> queryBoAllListBackend(Integer pageNum, Integer pageSize, CommunicateInfo communicateInfo) {
        Map<String, Object> map = new HashMap<>();

        Page<CommunicateInfo> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<CommunicateInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CommunicateInfo::getType, "2");
        wrapper.eq(CommunicateInfo::getCompanyId, communicateInfo.getCompanyId());
        wrapper.eq(CommunicateInfo::getIsDel, "0");
        if (StrUtil.isNotBlank(communicateInfo.getCompanyName())) {
            wrapper.like(CommunicateInfo::getCompanyName, communicateInfo.getCompanyName());
        }
        if (StrUtil.isNotBlank(communicateInfo.getProductName())) {
            wrapper.like(CommunicateInfo::getProductName, communicateInfo.getProductName());
        }
        if (StrUtil.isNotBlank(communicateInfo.getStatus())) {
            wrapper.eq(CommunicateInfo::getStatus, communicateInfo.getStatus());
        }
        Page<CommunicateInfo> pageResult = this.page(page, wrapper);

        map.put("total", pageResult.getTotal());
        map.put("list", pageResult.getRecords());

        return map;
    }


    /***
     * 查询员工的商机数量
     * @return
     * @param page
     * @param dto
     * @param userId
     */
    @Override
    public List<EmployeeOpportunityCountVo> queryCommunicateCountList(Page<EmployeeOpportunityCountVo> page, CommunicateInfoDto dto, String userId) {
        String enterpriseId = "";


        String roleIds = dto.getRoleIds();
        String[] roleIdArgs = roleIds.split(",");
        //企业用户分支
        if (ArrayUtil.containsAny(roleIdArgs, "8836c75af939406a9f41128826f6d8b3")) {
            Message message = luLianService.queryEnterpriseIdByUserId(userId);
            if (message.getCode() == 1) {
                return new ArrayList<EmployeeOpportunityCountVo>();
            }
            enterpriseId = (String) message.getObj();
        } else if (ArrayUtil.containsAny(roleIdArgs, "24d3f470d5784d2ba5f11f70f0b66af5")) {
            //非企业角色分支
        } else {
            throw new RuntimeException("未找到用户的角色");
        }
        List<EmployeeOpportunityCountVo> list = communicateInfoMapper.queryCommunicateCountList(page, dto, enterpriseId, userId);
        if (list != null && list.size() > 0) {
            String ids = list.stream().map(EmployeeOpportunityCountVo::getEmployeeName).collect(Collectors.joining(","));
            Message userList = scaleUserService.getUserList(ids);
            if (userList.getCode() == 1) {
                throw new RuntimeException("没有找到用户名称数据");
            }
            List<LinkedHashMap> obj = (List<LinkedHashMap>) userList.getObj();
            if (obj != null && obj.size() > 0) {
                Map<String, String> userMap = obj.stream().collect(Collectors.toMap(k -> (String) k.get("baseId"), v -> v.get("nickname") == null ? v.get("username").toString() : v.get("nickname").toString()));
                list.forEach(item -> {
                    if (userMap.containsKey(item.getEmployeeName())) {
                        item.setEmployeeName(userMap.get(item.getEmployeeName()));
                    }
                });
            }
        }
        return list;
    }

    @Override
    public Map<String, Long> queryCommunicateCount(String userId, CommunicateInfoDto dto) {
        String enterpriseId = "";

        String roleIds = dto.getRoleIds();
        String[] roleIdArgs = roleIds.split(",");
        Map<String, Long> map = new HashMap<>();
        //企业用户分支
        if (ArrayUtil.containsAny(roleIdArgs, "8836c75af939406a9f41128826f6d8b3")) {
            Message message = luLianService.queryEnterpriseIdByUserId(userId);
            if (message.getCode() == 1) {
                map.put("totalCount", 0L);
                map.put("gouTongCount", 0L);
                map.put("wanChengCount", 0L);
                return map;
            }
            enterpriseId = (String) message.getObj();
        } else if (ArrayUtil.containsAny(roleIdArgs, "24d3f470d5784d2ba5f11f70f0b66af5")) {
            //非企业角色分支
        } else {
            throw new RuntimeException("未找到用户的角色");
        }
        map = communicateInfoMapper.queryCommunicateCount(enterpriseId, userId);
        return map;
    }

    @Override
    public Message detailInfo(String baseId) {
        List<CardBusinessCollaborator> collaboratorList =  cardBusinessCollaboratorService.list(new LambdaQueryWrapper<CardBusinessCollaborator>().eq(CardBusinessCollaborator::getRelateId, baseId));
        CommunicateInfoVo communicateInfoVo = this.getBaseMapper().detailInfo(baseId);
        if(communicateInfoVo != null){
            communicateInfoVo.setCollaboratorList(collaboratorList);
        }
        return Message.success(communicateInfoVo);
    }

    @Override
    public Message listPage(Page page, CommunicateInfoDto dto) {
        String roleIds = dto.getRoleIds();
        String userId = dto.getUserId();
        String dateFilterType = dto.getDateFilterType();
        if(StringUtils.isEmpty(roleIds)){
            Message userRoleMessage = cloudShowManagerSubService.getRoleByUserId(userId);
            if (userRoleMessage == null) {
                return Message.fail("获取角色信息失败！");
            }
            roleIds = (String)userRoleMessage.getObj();

            if(userRoleMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                throw new RuntimeException("查询用户失败");
            }

        }
        if(!StringUtils.isEmpty(roleIds)) {
            String[] split = roleIds.split(StrUtil.COMMA);
            boolean systemAdmin = Arrays.stream(split).filter(f->"1".equals(f)).count() > 0;
            dto.setSystemAdmin(systemAdmin);
            if(!systemAdmin) {
                Message message = cloudShowManagerSubService.getUserInfo(userId);
                if (message == null) {
                    return Message.fail("获取认证企业信息失败！");
                }
                Object obj = message.getObj();
                if (obj == null) {
                    return Message.fail("获取认证企业信息失败！");
                }
                if (message.getCode() == 1) {
                    return Message.fail("查询用户信息错误");
                }
                //查询当前公司
                LuLianEnterprise luLianEnterprise = luLianService.selectCurrentUserJoinEnterpriseInfo(dto.getUserId());
                if(luLianEnterprise != null) {
                    String enterpriseId = luLianEnterprise.getBaseId();
                    dto.setCompanyId(enterpriseId);
                }
                ObjectMapper mapper = new ObjectMapper();
                Map resultMap = mapper.convertValue(obj, Map.class);
                //String deptPermission = (String)resultMap.get("deptPermission");
                String deptPermission = "";
                //获取当前用户的权限
                Message userAccessScopeMessage = cloudShowManagerSubService.queryUserAccessScope(userId);
                if (userAccessScopeMessage == null) {
                    throw new RuntimeException("获取用户权限失败");
                } else if (! userAccessScopeMessage.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
                    throw new RuntimeException("查询用户权限失败");
                } else {
                    deptPermission = (String) userAccessScopeMessage.getObj();
                }
                String deptId = (String)resultMap.get("deptId");
                dto.setDeptPermission(deptPermission);
                dto.setDeptId(deptId);
                List<String> deptList = new ArrayList();
                if(!StringUtils.isEmpty(deptId)){
                    deptList.add(deptId);
                    Message deptMessage = cloudShowManagerSubService.getSubDeptByDeptId(deptId);
                    if(deptMessage==null || deptMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                        throw new RuntimeException("查询子级部门失败");
                    }
                    String deptObj = (String)deptMessage.getObj();
                    if(StringUtils.isNotBlank(deptObj)){
                        String[] deptSplit = deptObj.split(StrUtil.COMMA);
                        for(String temp : deptSplit){
                            deptList.add(temp);
                        }
                    }

                }
                dto.setDeptList(deptList);
                String filterDeptId = dto.getFilterDeptId();
                List<String> filterDeptList = new ArrayList();
                if(!StringUtils.isEmpty(filterDeptId)){
                    filterDeptList.add(filterDeptId);
                    Message deptMessage = cloudShowManagerSubService.getSubDeptByDeptId(filterDeptId);
                    if(deptMessage==null || deptMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                        throw new RuntimeException("查询子级部门失败");
                    }
                    String deptObj = (String)deptMessage.getObj();
                    if(StringUtils.isNotBlank(deptObj)){
                        String[] deptSplit = deptObj.split(StrUtil.COMMA);
                        for(String temp : deptSplit){
                            filterDeptList.add(temp);
                        }
                    }
                }
                dto.setFilterDeptIdList(filterDeptList);
            }

        }
        Date beginDate = dto.getBeginDate();
        Date endDate = dto.getEndDate();
        if(beginDate != null){
            beginDate = DateUtil.beginOfDay(beginDate);
            dto.setBeginDate(beginDate);
        }
        if(endDate != null){
            endDate = DateUtil.endOfDay(endDate);
            dto.setEndDate(endDate);
        }
        if(!StringUtils.isEmpty(dateFilterType)){
            Map<String, DateTime> beginAndEnd = DateFilterUtil.getBeginAndEnd(dateFilterType);
            dto.setBeginDate(beginAndEnd.get("begin"));
            dto.setEndDate(beginAndEnd.get("end"));
        }
        List<CommunicateInfoVo> communicateInfoVos = this.getBaseMapper().communicatePage(page, dto);
        page.setRecords(communicateInfoVos);
        return Message.success(page);
    }

    @Override
    public Message confirm(CommunicateInfoSaveDto communicateInfoDto) {
        String baseId = communicateInfoDto.getBaseId();
        LambdaUpdateWrapper<CommunicateInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(CommunicateInfo::getConfirmStatus, "1").eq(CommunicateInfo::getBaseId, baseId);
        this.update(wrapper);
        return Message.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message saveCommunicateInfo(CommunicateInfoSaveDto communicateInfoDto) {
        try {
            if (communicateInfoDto == null || BeanUtil.isEmpty(communicateInfoDto) || StrUtil.isBlank(communicateInfoDto.getCompanyId())) {
                log.error("【addBusinessOpportunity】方法保存异常：===》入参异常");
                return Message.fail("入参异常");
            }
            //检查当前是否已有用户登录
            String userId = communicateInfoDto.getUserId();
            if (StrUtil.isNotBlank(userId)) {

                String baseId = communicateInfoDto.getBaseId();
                if(StringUtils.isEmpty(baseId)){
                    communicateInfoDto.setCreator(userId);
                }else{
                    communicateInfoDto.setUpdateBy(userId);
                }
//                //通过远程调用获取该用户的认证企业信息
//                Message message = enterpriseUserService.queryEnterpriseNameByUserId(userId);
//                if (message == null) {
//                    return Fail("获取认证企业信息失败！");
//                }
//                Object obj = message.getObj();
//                if (obj == null) {
//                    return Fail("获取认证企业信息失败！");
//                }
//                if (message.getCode() == 1) {
//                    return Fail(obj);
//                }
//                Map<String, String> queryMap = (Map) obj;
//                String companyId = queryMap.get("baseid");
//                communicateInfo.setCompanyId(companyId);
            } else {
                log.error("------------------未登录------------------");
                return Message.fail("请先登录！");
            }
            List<String> collactorIdList = communicateInfoDto.getCollaboratorIdList();
            String directorId = communicateInfoDto.getDirectorId();
            if(!CollectionUtils.isEmpty(collactorIdList) && !StringUtils.isEmpty(directorId) && collactorIdList.contains(directorId)){
                return Message.fail("协作人不能包含负责人");
            }
            //查询商机名称是否存在
            List<CommunicateInfo> list = this.list(new LambdaQueryWrapper<CommunicateInfo>().eq(CommunicateInfo::getProductName, communicateInfoDto.getProductName()).eq(CommunicateInfo::getCompanyId, communicateInfoDto.getCompanyId()));
            if(!CollectionUtils.isEmpty(list)){
                if(StringUtils.isEmpty(communicateInfoDto.getBaseId())){
                    return Message.fail("商机标题已存在！");
                }else {
                    long existCount = list.stream().filter(f -> !f.getBaseId().equals(communicateInfoDto.getBaseId())).count();
                    if(existCount > 0){
                        return Message.fail("商机标题已存在！");
                    }
                }
            }
            //设置类型为后台新增的商机
            communicateInfoDto.setType("2");
            //设置合同确认状态
            communicateInfoDto.setConfirmStatus("0");
            //进行数据存储
            CommunicateInfo communicateInfo = new CommunicateInfo();
            BeanUtils.copyProperties(communicateInfoDto, communicateInfo);
            if(!StringUtils.isEmpty(communicateInfo.getBaseId()) && "f10de0bf5e53a13ea32711023624111330".equals(communicateInfo.getTransactionProgress())){
                //修改时如果商机进度为100%，则商机状态为赢单
                communicateInfo.setCommunicateStatus("f10de0bf5e53a13ea32711023624111335");
            }
            if(!StringUtils.isEmpty(communicateInfo.getBaseId()) && "f10de0bf5e53a13ea32711023624111335".equals(communicateInfo.getCommunicateStatus())){
                //修改时如果商机状态为赢单,则商机进度为100%
                communicateInfo.setTransactionProgress("f10de0bf5e53a13ea32711023624111330");
            }
            if (this.saveOrUpdate(communicateInfo)) {
                cardBusinessCollaboratorService.remove(new LambdaQueryWrapper<CardBusinessCollaborator>().eq(CardBusinessCollaborator::getRelateId, communicateInfo.getBaseId()));

                if(!CollectionUtils.isEmpty(collactorIdList)){
                    String collactorIds = String.join(",", collactorIdList);
                    Message userMessage = cloudShowManagerSubService.getUserList(collactorIds);
                    if(userMessage == null || userMessage.getCode() == 1){
                        throw new RuntimeException("员工信息获取失败");
                    }

                    List<LinkedHashMap> userInfoList = (List<LinkedHashMap>)userMessage.getObj();
                    if(userInfoList != null && !userInfoList.isEmpty()){
                        Map<Object, LinkedHashMap> userMap = userInfoList.stream().collect(Collectors.toMap(k ->
                                        k.get("baseId"),
                                v -> v,
                                (existing, replacement) -> existing
                        ));
                        List collactorList = new ArrayList();
                        for (String collactorId : collactorIdList) {
                            LinkedHashMap map = userMap.get(collactorId);
                            CardBusinessCollaborator cardBusinessCollaborator = new CardBusinessCollaborator();
                            cardBusinessCollaborator.setCompanyId(communicateInfo.getCompanyId());
                            cardBusinessCollaborator.setUserId(collactorId);
                            cardBusinessCollaborator.setRelateId(communicateInfo.getBaseId());
                            cardBusinessCollaborator.setUserName(map.get("realname") == null ? "" : map.get("realname").toString());
                            cardBusinessCollaborator.setDeptId(map.get("deptId") == null ? "" : map.get("deptId").toString());
                            collactorList.add(cardBusinessCollaborator);
                        }
                        if(!CollectionUtils.isEmpty(collactorList)){
                            cardBusinessCollaboratorService.saveBatch(collactorList);
                        }
                    }


                }
                return Message.success("保存商机成功！");
            } else {
                return Message.fail("保存商机失败！");
            }
        } catch (Exception e) {
            log.error("保存商机异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    @Override
    public Message deptAdmin(String userId) {
        Message message = cloudShowManagerSubService.getUserInfo(userId);
        if (message == null) {
            return Message.fail("获取认证企业信息失败！");
        }
        Object obj = message.getObj();
        if (obj == null) {
            return Message.fail("获取认证企业信息失败！");
        }
        if (message.getCode() == 1) {
            return Message.fail("查询用户信息错误");
        }
        ObjectMapper mapper = new ObjectMapper();
        Map resultMap = mapper.convertValue(obj, Map.class);
        String deptPermission = (String)resultMap.get("deptPermission");
        return Message.success("1".equals(deptPermission));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message dispatch(CommunicateInfoSaveDto communicateInfoDto) {
        String baseId = communicateInfoDto.getBaseId();
        String[] split = baseId.split(StrUtil.COMMA);

        //删除对应协作人
        LambdaQueryWrapper<CardBusinessCollaborator> businessCollaboratorWrapper = new LambdaQueryWrapper<>();
        businessCollaboratorWrapper.eq(CardBusinessCollaborator::getUserId,communicateInfoDto.getDirectorId()).in(CardBusinessCollaborator::getRelateId, Arrays.asList(split));
        cardBusinessCollaboratorService.remove(businessCollaboratorWrapper);
        LambdaUpdateWrapper<CommunicateInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(CommunicateInfo::getDirectorId, communicateInfoDto.getDirectorId())
                .set(CommunicateInfo::getDeptId, communicateInfoDto.getDeptId())
                .set(CommunicateInfo::getDirectorName, communicateInfoDto.getDirectorName())
                .set(CommunicateInfo::getBaseUpdateTime, new Date())
                .set(CommunicateInfo::getUpdateBy, communicateInfoDto.getUserId())
                .in(CommunicateInfo::getBaseId, Arrays.asList(split));
        this.update(wrapper);
        return Message.success();
    }

    @Override
    public Message updateCommunicateInfo(CommunicateInfoSaveDto communicateInfoDto) {
        String field = communicateInfoDto.getField();
        String filedValue = communicateInfoDto.getFieldValue();
        List<String> idList = communicateInfoDto.getIdList();
        if(!StringUtils.isEmpty(field) && !StringUtils.isEmpty(filedValue)){
            UpdateWrapper<CommunicateInfo> wrapper = new UpdateWrapper<>();
            field = StrUtil.toUnderlineCase(field);
            wrapper.set(field, filedValue).in("base_id", idList);
            this.update(wrapper);
        }else{
            return Message.fail("请重新编辑字段！");
        }

        return Message.success();
    }

    @Override
    public Message importExcel(CommunicateInfoSaveDto communicateInfoDto) {
        MultipartFile file = communicateInfoDto.getFile();
        List<String> errorMessageList = new ArrayList();
        List<CommunicateInfoImportDto> fileImportList = new ArrayList<>();
        try{
            EasyExcel.read(file.getInputStream(), CommunicateInfoImportDto.class, new ReadListener<CommunicateInfoImportDto>(){

                @Override
                public void invoke(CommunicateInfoImportDto importData, AnalysisContext analysisContext) {

                    fileImportList.add(importData);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {

                }
            }).sheet().doRead();
            if(fileImportList.isEmpty()){
                return Message.fail("文件中没有找到数据");
            }else{
                List<CommunicateInfoImportDto> importList = fileImportList.stream().filter(f->!StringUtils.isEmpty(f.getProductName())).collect(Collectors.toList());
                if(importList.isEmpty()){
                    return Message.fail("文件中没有找到数据");
                }
                if(importList.size() > 500){
                    return Message.fail("导入数据不能超过500条");
                }
                Message message = cloudShowManagerSubService.getUserInfo(communicateInfoDto.getUserId());
                if (message == null) {
                    return Message.fail("获取用户信息失败！");
                }
                Object obj = message.getObj();
                if (obj == null) {
                    return Message.fail("获取用户信息失败！");
                }
                if (message.getCode() == 1) {
                    return Message.fail("查询用户信息错误");
                }
                ObjectMapper mapper = new ObjectMapper();
                Map resultMap = mapper.convertValue(obj, Map.class);
                String deptId = (String)resultMap.get("deptId");
                String currentRealName = (String)resultMap.get("realname");
                //查询当前公司
                LuLianEnterprise luLianEnterprise = luLianService.selectCurrentUserJoinEnterpriseInfo(communicateInfoDto.getUserId());
                if(luLianEnterprise != null){
                    String enterpriseId = luLianEnterprise.getBaseId();
                    List<String> businessNameList = importList.stream().map(m -> m.getProductName()).collect(Collectors.toList());
                    List<CommunicateInfo> existList = this.list(new LambdaQueryWrapper<CommunicateInfo>().in(CommunicateInfo::getProductName, businessNameList).eq(CommunicateInfo::getCompanyId, enterpriseId));
                    Map<String, String> businessRecordMap = new HashMap<>();
                    if(!CollectionUtils.isEmpty(existList)){
                        businessRecordMap = existList.stream()
                                .collect(Collectors.toMap(
                                        CommunicateInfo::getProductName,
                                        CommunicateInfo::getBaseId,
                                        (existing, replacement) -> existing
                                ));
                    }
                    List<SysData> saleStageList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "COMMUNICATE_STATUS"));
                    Map<String, String> stageMap = saleStageList.stream().collect(Collectors.toMap(
                            SysData::getBaseName,
                            SysData::getBaseId,
                            (existing, replacement) -> existing
                    ));
                    List<SysData> businessTypeList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "COMMUNICATE_TYPE"));
                    Map<String, String> businessTypeMap = businessTypeList.stream().collect(Collectors.toMap(
                            SysData::getBaseName,
                            SysData::getBaseId,
                            (existing, replacement) -> existing
                    ));

                    List<SysData> businessSourceList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "COMMUNICATE_SOURCE"));
                    Map<String, String> businessSourceMap = businessSourceList.stream().collect(Collectors.toMap(
                            SysData::getBaseName,
                            SysData::getBaseId,
                            (existing, replacement) -> existing
                    ));

                    List<CommunicateInfo> communicateInfoList = new ArrayList<>();
                    String overrideFlag = communicateInfoDto.getOverrideFlag();
                    for(int i = importList.size()-1; i >= 0; i--){
                        CommunicateInfoImportDto importData = importList.get(i);
                        CommunicateInfo communicateInfo = new CommunicateInfo();
                        BeanUtils.copyProperties(importData, communicateInfo);
                        communicateInfo.setCompanyId(enterpriseId);
                        communicateInfo.setCompanyName(luLianEnterprise.getBaseName());
                        if(businessRecordMap.get(importData.getProductName()) != null){
                            if("1".equals(overrideFlag)){
                                //覆盖
                                communicateInfo.setBaseUpdateTime(new Date());
                                communicateInfo.setUpdateBy(communicateInfoDto.getUserId());
                                communicateInfo.setDeptId(deptId);
                                communicateInfo.setBaseId(businessRecordMap.get(importData.getProductName()));
                            }else{
                                //不覆盖
                                errorMessageList.add("商机名称："+importData.getProductName()+"已存在");
                                continue;
                            }
                        }else{
                            communicateInfo.setCreator(communicateInfoDto.getUserId());
                            communicateInfo.setDeptId(deptId);
                        }
                        communicateInfo.setDirectorId(communicateInfoDto.getUserId());
                        communicateInfo.setDirectorName(currentRealName);
                        //设置类型为后台新增的商机
                        communicateInfo.setType("2");
                        //设置合同确认状态
                        communicateInfo.setConfirmStatus("0");
                        if(stageMap.get(communicateInfo.getCommunicateStatus()) != null){
                            communicateInfo.setCommunicateStatus(stageMap.get(communicateInfo.getCommunicateStatus()));
                        }else{
                            if(!StringUtils.isEmpty(communicateInfo.getCommunicateStatus())){
                                errorMessageList.add("商机名称："+communicateInfo.getProductName()+"销售阶段："+communicateInfo.getCommunicateStatus()+"不存在");
                                continue;
                            }

                        }
                        if(businessSourceMap.get(communicateInfo.getCommunicateSource()) != null){
                            communicateInfo.setCommunicateSource(businessSourceMap.get(communicateInfo.getCommunicateSource()));
                        }else{
                            if(!StringUtils.isEmpty(communicateInfo.getCommunicateSource())){
                                errorMessageList.add("商机名称："+communicateInfo.getProductName()+"商机来源："+communicateInfo.getCommunicateSource()+"不存在");
                                continue;
                            }

                        }
                        if(businessTypeMap.get(communicateInfo.getCommunicateType()) != null){
                            communicateInfo.setCommunicateType(businessTypeMap.get(communicateInfo.getCommunicateType()));
                        }else{
                            if(!StringUtils.isEmpty(communicateInfo.getCommunicateType())){
                                errorMessageList.add("商机名称："+communicateInfo.getProductName()+"商机类型："+communicateInfo.getCommunicateType()+"不存在");
                                continue;
                            }

                        }

                        communicateInfoList.add(communicateInfo);

                    }
                    if(!CollectionUtils.isEmpty(communicateInfoList)){
                        this.saveOrUpdateBatch(communicateInfoList);
                    }

                }else{
                    return Message.fail("当前用户没有加入公司");
                }

            }
        }catch (Exception e){
            errorMessageList.add(e.getMessage());
        }
        if(!CollectionUtils.isEmpty(errorMessageList)){
            return Message.fail(errorMessageList);
        }else{
            return Message.success();
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message deleteCommunicateInfo(String baseId) {
        String[] split = baseId.split(StrUtil.COMMA);
        this.removeByIds(Arrays.asList(split));
        cardBusinessCollaboratorService.remove(new LambdaQueryWrapper<CardBusinessCollaborator>().in(CardBusinessCollaborator::getRelateId, Arrays.asList(split)));
        return Message.success();
    }

    @Override
    public List<CommunicateInfoExportVo> communicateInfoList(CommunicateInfoDto dto) {
        String roleIds = dto.getRoleIds();
        String userId = dto.getUserId();
        String dateFilterType = dto.getDateFilterType();
        if(StringUtils.isEmpty(roleIds)){
            Message userRoleMessage = cloudShowManagerSubService.getRoleByUserId(userId);
            if (userRoleMessage == null) {
                throw new RuntimeException("获取角色信息失败");
            }
            roleIds = (String)userRoleMessage.getObj();

            if(userRoleMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                throw new RuntimeException("查询用户失败");
            }

        }
        if(!StringUtils.isEmpty(roleIds)) {
            String[] split = roleIds.split(StrUtil.COMMA);
            boolean systemAdmin = Arrays.stream(split).filter(f->"1".equals(f)).count() > 0;
            dto.setSystemAdmin(systemAdmin);
            if(!systemAdmin) {
                Message message = cloudShowManagerSubService.getUserInfo(userId);
                if (message == null) {
                    throw new RuntimeException("获取用户信息失败");

                }
                Object obj = message.getObj();
                if (obj == null) {
                    throw new RuntimeException("获取用户信息失败");

                }
                if (message.getCode() == 1) {
                    throw new RuntimeException("查询用户信息错误");

                }
                //查询当前公司
                LuLianEnterprise luLianEnterprise = luLianService.selectCurrentUserJoinEnterpriseInfo(dto.getUserId());
                if(luLianEnterprise != null) {
                    String enterpriseId = luLianEnterprise.getBaseId();
                    dto.setCompanyId(enterpriseId);
                }
                ObjectMapper mapper = new ObjectMapper();
                Map resultMap = mapper.convertValue(obj, Map.class);
                String deptPermission = (String)resultMap.get("deptPermission");
                //获取当前用户的权限
                Message userAccessScopeMessage = cloudShowManagerSubService.queryUserAccessScope(userId);
                if (userAccessScopeMessage == null) {
                    throw new RuntimeException("获取用户权限失败");
                } else if (! userAccessScopeMessage.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
                    throw new RuntimeException("查询用户权限失败");
                } else {
                    deptPermission = (String) userAccessScopeMessage.getObj();
                }
                String deptId = (String)resultMap.get("deptId");
                dto.setDeptPermission(deptPermission);
                dto.setDeptId(deptId);
                List<String> deptList = new ArrayList();
                if(!StringUtils.isEmpty(deptId)){
                    deptList.add(deptId);
                    Message deptMessage = cloudShowManagerSubService.getSubDeptByDeptId(deptId);
                    if(deptMessage==null || deptMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                        throw new RuntimeException("查询子级部门失败");
                    }
                    String deptObj = (String)deptMessage.getObj();
                    if(StringUtils.isNotBlank(deptObj)){
                        String[] deptSplit = deptObj.split(StrUtil.COMMA);
                        for(String temp : deptSplit){
                            deptList.add(temp);
                        }
                    }

                }
                dto.setDeptList(deptList);
                String filterDeptId = dto.getFilterDeptId();
                List<String> filterDeptList = new ArrayList();
                if(!StringUtils.isEmpty(filterDeptId)){
                    filterDeptList.add(filterDeptId);
                    Message deptMessage = cloudShowManagerSubService.getSubDeptByDeptId(filterDeptId);
                    if(deptMessage==null || deptMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                        throw new RuntimeException("查询子级部门失败");
                    }
                    String deptObj = (String)deptMessage.getObj();
                    if(StringUtils.isNotBlank(deptObj)){
                        String[] deptSplit = deptObj.split(StrUtil.COMMA);
                        for(String temp : deptSplit){
                            filterDeptList.add(temp);
                        }
                    }
                }
                dto.setFilterDeptIdList(filterDeptList);
            }

        }

        Date beginDate = dto.getBeginDate();
        Date endDate = dto.getEndDate();
        if(beginDate != null){
            beginDate = DateUtil.beginOfDay(beginDate);
            dto.setBeginDate(beginDate);
        }
        if(endDate != null){
            endDate = DateUtil.endOfDay(endDate);
            dto.setEndDate(endDate);
        }
        if(!StringUtils.isEmpty(dateFilterType)){
            Map<String, DateTime> beginAndEnd = DateFilterUtil.getBeginAndEnd(dateFilterType);
            dto.setBeginDate(beginAndEnd.get("begin"));
            dto.setEndDate(beginAndEnd.get("end"));
        }
        List<CommunicateInfoExportVo> resultList = this.getBaseMapper().communicateList(dto);

        return resultList;
    }

    @Override
    public Message saveCommunicateInfoNonCheck(CommunicateInfoSaveDto communicateInfoDto) {
        try {
            String directorId = communicateInfoDto.getDirectorId();
            if (StrUtil.isBlank(communicateInfoDto.getCompanyId())) {
                LuLianEnterpriseUser enterpriseUser = luLianEnterpriseUserService.getOne(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", directorId));
                if(enterpriseUser != null){
                    String enterpriseId = enterpriseUser.getEnterpriseId();
                    communicateInfoDto.setCompanyId(enterpriseId);
                }else{
                    return Message.fail("获取所选负责人企业信息失败！");
                }
            }

            //查询商机名称是否存在
            String productName = communicateInfoDto.getProductName();
            List<CommunicateInfo> list = this.baseMapper.selectListBusiness(communicateInfoDto);
            if (list.size() > 0) {
                //如果名称重复则进行处理
                String existingProductName = list.get(0).getProductName();
                String substring = existingProductName.substring(productName.length());
                if (StrUtil.isNotBlank(substring)) {
                    //如果最后以数字结尾，则将该数字递增后组成新名称
                    int sort = Integer.valueOf(substring) + 1;
                    productName = productName + sort;
                } else {
                    //如果最后以汉字结尾，则将数字1添加至末尾组成新名称
                    productName = productName + 1;
                }
                communicateInfoDto.setProductName(productName);
            }

            communicateInfoDto.setCreator(communicateInfoDto.getUserId());
            communicateInfoDto.setBaseCreateTime(new Date());
            //设置类型为后台新增的商机
            communicateInfoDto.setType("2");
            //设置合同确认状态
            communicateInfoDto.setConfirmStatus("0");
            //进行数据存储
            CommunicateInfo communicateInfo = new CommunicateInfo();
            BeanUtils.copyProperties(communicateInfoDto, communicateInfo);
            this.save(communicateInfo);
            return Message.success();
        } catch (Exception e) {
            log.error("保存商机异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }



    /*private boolean  isEnterpriseAdmin(String userId){
        List<SysRole> list = this.getBaseMapper().findRoleByUserId(userId);
        if(!CollectionUtils.isEmpty(list)){
            long count = list.stream().filter(f -> StringUtils.equalsAny(f.getBaseId(), "043ea2e3e02c4aa591df1f83e65069bc", "0a2538ddcd20455ba4c105e83f9872c3")).count();
            return count > 0;

        }else{
            return false;
        }
    }*/



}